<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { allSvcProvider } from '@/api/SvcProvider'
import { appStore } from '@/stores/appStore/appStore'
import { commonStore } from '@/stores/commonStore/commonStore'
const app = appStore()
let showPicker = ref(false)
let columns = ref() 
const props = defineProps({
    cityName: {
        type: String,
        default: '未定位'
    },
    modelValue: {
        type: String,
        default: ''
    }
})
const emits = defineEmits(['onSearch', 'onCancel', 'update:modelValue' ,'onChange'])
onMounted(() => {
    type providerList = {
        cityName: string,
        id: string,
    }
    if (app.providerList.length === 0) {
        getProviderList()
    } else {
        let array: string[] = []
        app.providerList.forEach((item: providerList) => {
            array.push(item.cityName)        
        })
        columns.value = array
    }
})

const content = computed({
    get: () => {
        return props.modelValue
    },
    set: (val) => {
        emits('update:modelValue', val)
    }
})
function getProviderList() {
    type providerList = {
        cityName: string,
        id: string,
    }
    allSvcProvider().then((res: { data: providerList[] }) => {
        let array: string[] = []
        res.data.forEach((item: providerList) => {
            let { cityName, id } = item
            app.providerList.push({ cityName, id })
            array.push(cityName)
        })
        columns.value = array
    })
}
function onSearch() {
    emits('onSearch')
}
function onCancel() {
    emits('onCancel')
}

function onSelectCity(e: any) {
    showPicker.value = false
    let curCity = app.providerList.find((item) => {
        return item.cityName === e
    })
    if (curCity) {
        app.svcProviderId = curCity.id
    }
    emits('onChange', e)
}
</script>
<template>
    <form action="/" class="search-box">
        <van-search v-model="content" show-action placeholder="请输入搜索关键词" :background="commonStore().themeColorValue"
            @search="onSearch" @clear="onCancel" input-align="center">
            <template #left>
                <div class="i-text-14 i-mr-10 text-white" @click="showPicker = true">{{ props.cityName }}</div>
            </template>
            <template #action >
                <div class="i-text-14  text-white" @click="onSearch">搜索</div>
            </template>
        </van-search>
    </form>
    <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker title="选择城市" @confirm="onSelectCity" :columns="columns" @cancel="showPicker = false" />
    </van-popup>
</template>
<style>
.van-search__content {
    border-radius: 30px;
}

.search-box {
    position: sticky;
    z-index: 10;
    top: 0;
    left: 0;
}

.van-search__action:active {
    background-color: transparent;
}
</style>